<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
    <div class="links">
      <a href="/register">注册</a>
      <a href="/forgot">忘记密码</a>
      <a href="/adminLogin">管理员登录</a>
    </div>
  </div>
</template>
  
<script setup>
import { ref, onBeforeMount } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const username = ref('');
const password = ref('');

// 设置token到localStorage
function setAuthToken(token, tokenHead) {
  axios.defaults.headers.common['Authorization'] = `${tokenHead} ${token}`;
  localStorage.setItem('authToken', token);
  localStorage.setItem('Bearer', tokenHead);
}

// 检查localStorage中的token并自动登录
function autoLogin() {
  const token = localStorage.getItem('authToken');
  const tokenHead = localStorage.getItem('Bearer');
  if (token && tokenHead) {
    //console.log('haha')
    router.push({ name: 'home' });
  }
}

// axios响应拦截器
axios.interceptors.response.use(
  response => {
    // 检查response中是否包含特定的错误信息
    if (response.data && response.data.code === 500 && response.data.message === "未登录") {
      // 这里处理未登录的情况
      localStorage.removeItem('authToken');
      localStorage.removeItem('Bearer');
      router.push({ name: 'login' });
    }
    return response;
  },
  error => {
    // 检查是否存在error.response
    if (error.response) {
      
    }
    return Promise.reject(error);
  }
);

// 在组件挂载前调用autoLogin
 onBeforeMount(autoLogin);

const handleLogin = async () => {
  try {
    const response = await axios.post('http://8.219.49.219:8080/onlineShopping/user/login', {
      username: username.value,
      password: password.value
    }, {
      withCredentials: true
    });
    // console.log(response)
    // 检查响应代码是否为200
    if (response.data.code === 200) {
      // 检查data对象中的state属性是否为true
      if (response.data.data.state) {
        // 登录成功，处理token等逻辑
        const token = response.data.data.token;
        const tokenHead = response.data.data.tokenHead;
        // console.log(token + tokenHead);
        // 在这里设置token到localStorage
        setAuthToken(token, tokenHead);
        // console.log('Login successful:', token);
        // 跳转到主页
        router.push({ name: 'home' });
      } else {
        // 登录失败，处理错误
        console.error('Login failed:', response.data.message);
      }
    } else {
      // 响应代码不是200，处理错误
      console.error('Error:', response.data.message);
      alert('用户名或密码错误')
    }
  } catch (error) {
    // 处理请求错误
    console.error('Error during login:', error);
  }
};
  </script>
  
  <style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.8); 
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  text-align: center;
  color: #333; 
  background-image: url('/pictures/bg.jpg'); 
  background-size: cover; 
  background-position: center; 
  background-blend-mode: multiply; 
}

.login-container h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-family: 'Roboto', sans-serif; 
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 16px;
  color: #666;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  background-color: #f8f8f8; 
  color: #333; 
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #4CAF50; 
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #45a049; 
}

.links {
  margin-top: 20px;
  text-align: center;
}

.links a {
  margin: 0 10px;
  color: #4CAF50; 
  text-decoration: none;
  font-size: 16px;
}

.links a:hover {
  text-decoration: underline;
}
</style>
  
